﻿$(document).ready(function () {
    if (typeof (DAY24H) == "undefined") {
        DAY24H = {};
    }
    var obj;
    DAY24H.Cart = (function () {
        var methods = {};
        methods.CartGrid = null;
        methods.Collection = null;
        var $table = $('#list-details,#list-detail-right');
        methods.buildGrid = function () {
            var productInCookie = $.JSONCookie('ProductStore');
            if (!!productInCookie['products'] && productInCookie['products'].length > 0) {
                $table.find('tbody').remove();
                var list = new CartCollection();
                var totalPrice = 0;
                var totalQuantity = 0;
                var stt = 1;
                _.each(productInCookie["products"], function (item) {
                    var dept = new Cart({
                        'stt': stt,
                        'id': item.Id,
                        'ShortName': item.ProductName,
                        'ProductName': item.ProductName,
                        'Quantity': item.Quantity,
                        'Price': item.Price == null ? 0 : item.Price,
                        'TotalPrice': item.TotalPrice == null ? 0 : item.TotalPrice,
                        'FormatPrice': $.formatNumber(item.Price, { format: "#,###", locale: "us" }),
                        'FormatTotalPrice': $.formatNumber(item.TotalPrice, { format: "#,###", locale: "us" })
                    });
                    stt += 1;
                    totalPrice += item.TotalPrice;
                    totalQuantity += item.Quantity;
                    list.push(dept);
                });
                $('#cart_right').fadeIn("fast");
                $table.fadeIn();
                methods.Collection = list;
                methods.CartGrid = new CartGrid({ collection: list });
                $table.append(methods.CartGrid.render().el);
                $(".cart-info").html('Giỏ :<span>' + totalQuantity + " SP</span> Tổng :<span>" + $.formatNumber(totalPrice, { format: "#,###", locale: "us" }) + " đ</span>");
                $(".cart-total, .cart_total_quantity").html(totalQuantity + ' sản phẩm');
                $(".total-price").html($.formatNumber(totalPrice, { format: "#,###", locale: "us" }) + ' Đ');
                $('.cart_total_price').html('Giá: <font color="#9f0401">' + $.formatNumber(totalPrice, { format: "#,###", locale: "us" }) + ' đ</font>');
                $(".payment-bar").show();

            } else {
                $('#cart_right').fadeOut("fast");
                $("#scroll-card").fadeOut("fast");
                $table.find('tbody').remove();
                productInCookie = { "products": [] };
                eval('obj = ' + JSON.stringify(productInCookie), window);
                $.JSONCookie('ProductStore', obj, { path: '/' });

                $(".cart-info").html('Giỏ :<span>Chưa có sản phẩm</span>');
                $(".cart-total, .cart_total_quantity").html('0 sản phẩm');
                $(".total-price").html('0 Đ');
                $('.cart_total_price').html('Giá: <font color="#9f0401">0 đ</font>');
                $(".payment-bar").hide();
            }
        };
        /*
        Hàm cập nhập dữ liệu trên trang sau khi save
        */
        methods.updateGrid = function (model, isNew) {
            $table.fadeIn("fast");
            if (isNew) {
                methods.Collection.add(model, { at: 0 });
            }
        };
        methods.Add2Cart = function (pId, quantity, imageContainer) {
            var session_level = $('#session_level').val();
            var session_idcuahang = $('#session_idcuahang').val();
            $.ajax({
                type: "POST",
                url: "/ManageCart/GetInfo",
                data: "{'id':'" + pId + "','level':'" + session_level + "','cuahangid':'" + session_idcuahang + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var product = response.d;
                    var priceItem;
                    // Kiểm tra số lượng tồn
                    if (product.Inventory === 0) {
                        MessageBoxWarning("Sản phẩm này tạm thời hết hàng.");
                        return false;
                    }
                    // Kiểm tra thành viên đăng nhập
                    var session_user = $('#session_user').val();
                    if (session_user == "" || session_user == undefined) {
                        $.messagers.confirmlogin('Nhắc nhở', 'Quý khách ĐĂNG NHẬP hoặc ĐĂNG KÝ thành viên để có giá tốt nhất?', function (r) {
                            if (r === 1) {
                                window.location = '/dang-nhap'; 
                            } else if (r === 2) {
                                window.location = '/dang-ky-thanh-vien';
                            }
                            else {
                                // Lấy giá lẻ
                                priceItem = product.Price == null ? 0 : product.Price;
                                methods.AddToCookie(imageContainer, product.Id, product.Name, quantity, priceItem);
                            }
                        });
                    } else {
                        // Lấy giá thành viên
                        priceItem = product.PriceMember == null ? 0 : product.PriceMember;
                        methods.AddToCookie(imageContainer, product.Id, product.Name, quantity, priceItem);
                    }
                },
                failure: function (msg) {
                    alert(msg);
                }
            });
        };

        methods.AddToCookie = function (imageContainer,id, name, quantity, price) {
            var img = $("#" + imageContainer).find('img:first');
            $("#cart_right").fadeIn("fast");
            $("#scroll-card").fadeOut("fast");
            flyToElement($(img), $('#cart_right'));
            var cookieName = 'ProductStore', productItem = { 'Id': id, 'ProductName': name, 'Quantity': quantity, 'Price': price, 'TotalPrice': price * quantity };
            var productCookie = { "products": [] };
            var o = $.JSONCookie(cookieName);
            if (o == null) {
                o = productCookie;
            }
            var isExists = false;
            $.each(o["products"], function (i, v) {
                if (v.Id == productItem.Id) {
                    isExists = true;
                    var q = v.Quantity + quantity;
                    v.Quantity = q;
                    v.Price = price;
                    v.TotalPrice = v.Price * q;
                    return false;
                }
            });
            if (!isExists) {
                o["products"].push(productItem);
            }
            eval('obj = ' + JSON.stringify(o), window);
            $.JSONCookie(cookieName, obj, { path: '/' });
            methods.buildGrid();
        };

        methods.RemoveCartItem = function (pId) {
            var cookieName = 'ProductStore';
            var productCookie = { "products": [] };
            var o = $.JSONCookie(cookieName);
            if (o == null) {
                o = productCookie;
            }
            var isExists = false;
            var eIndex = 0;
            $.each(o["products"], function (i, v) {
                if (v.Id == pId) {
                    isExists = true;
                    return false;
                }
                eIndex++;
            });
            if (isExists) {
                o["products"].splice(eIndex, 1);
            }

            eval('obj = ' + JSON.stringify(o), window);
            $.JSONCookie(cookieName, obj, { path: '/' });
            methods.buildGrid();
        };
        // quy ước về hàm khởi tạo
        methods.init = function () {
            methods.buildGrid();
            $(".add2cart").bind("click", function () {
                var pId = $(this).attr('data-id');
                var vQuantity = parseFloat($('#quantity_' + pId).val());
                methods.Add2Cart(pId, vQuantity, 'productImageWrapID_' + pId);
            });
            $("#button-cart").bind("click", function () {
                var pId = $(this).attr('data-id');
                var vQuantity = parseFloat($("#quantityNb").val());
                methods.Add2Cart(pId, vQuantity, 'productImageWrapID_' + pId);
            });
            $(".selectProduct:checkbox").bind("click", function () {
                var pId;
                if (this.checked) {
                    pId = $(this).val();
                    var vQuantity = 1;
                    methods.Add2Cart(pId, vQuantity, 'product_related_' + pId);
                } else {
                    pId = $(this).val();
                    methods.RemoveCartItem(pId);
                }
            });
        };
        return methods;
    })(DAY24H.Cart);
    DAY24H.Cart.init();
});
window.CartGrid = Backbone.View.extend({
    tagName: 'tbody',
    render: function () {
        $(this.el).html('');
        var i = 1;
        _.each(this.collection.models, function (sfunction) {
            $(this.el).append((new CartGridItem({ model: sfunction })).render().el);
            i++;
        }, this);
        return this;
    },
    initialize: function () {
        var self = this;
        this.collection.bind("reset", this.render, this);
        this.collection.bind("add", function (sfunction) {
            $(self.el).prepend(new CartGridItem({ model: sfunction }).render().el);
        });
    }
});
window.CartGridItem = Backbone.View.extend({
    tagName: 'tr',
    initialize: function () {
        this.model.bind("change", this.render, this);
        this.model.bind("destroy", this.close, this);
    },
    events: {
        'click .cr-drop': 'removeItem'
    },
    removeItem: function (event) {
        var self = this;
        var cookieName = 'ProductStore';
        var productCookie = { "products": [] };
        var o = $.JSONCookie(cookieName);
        if (o == null) {
            o = productCookie;
        }
        var isExists = false;
        var eIndex = 0;
        $.each(o["products"], function (i, v) {
            if (v.Id == self.model.get('id')) {
                isExists = true;
                return false;
            }
            eIndex++;
        });
        if (isExists) {
            o["products"].splice(eIndex, 1);
        }

        eval('obj = ' + JSON.stringify(o), window);
        $.JSONCookie(cookieName, obj, { path: '/' });
        DAY24H.Cart.buildGrid();
    },
    render: function () {
        this.template = _.template('<th width="6%" style="text-align:center;"><%=model.stt%></th><th class="cr-title"><span title="<%= model.ProductName%>"><%=model.ShortName%></span></th><th width="8%" class="cr-qty"><%=model.Quantity %></th><th width="23%" class="cr-pri" style="text-align:right;padding-right: 2px;"><%=model.FormatPrice%></th><th width="6%" class="cr-drop"><img src="/Content/images/close.png" alt="Xóa" title="Xóa" /></th>');
        $(this.el).html(this.template({ model: this.model.toJSON() }));
        return this;
    },
    close: function () {
        $(this.el).remove();
    }
});